package com.blog.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blog.domain.User;

public class PageFilter implements Filter {

	private static final String USER_TAG = "user";
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		setNoCache(res);
		
		System.out.println("request url:"+ ((HttpServletRequest) request).getRequestURL().toString());

		User u = WebUtils.getUser(req);
		if( (u != null) && (req.getAttribute(USER_TAG) == null) ){
			req.setAttribute(USER_TAG, u);
		}
		
		req.setAttribute("server", req.getServerName() + ( "80".equals(req.getServerPort()) ? "" : (":" + req.getServerPort())));
		req.setAttribute("begin", System.currentTimeMillis());

		chain.doFilter(req, res);
	}

	public void setNoCache(HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
		response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		response.setDateHeader("Expires", 0); // prevents caching at the proxy
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
